package com.oauth.TickGranter;

import com.oauth.dao.UserDao;
import com.oauth.entity.LoginUser;
import com.oauth.entity.User;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 可以用cas的票子或者短信登录等等，自己在authenticate(Authentication authentication)中实现就好
 * @author ysy
 */
@Setter
@Component
public class CasTickAuthenticationProvider implements AuthenticationProvider {


    @Autowired
    private UserDao userDao;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //此时principal是传进来的token，根据token查询用户编号
        Object principal = authentication.getPrincipal();
        String ticket =principal.toString();
        String userName =ticketValidator(ticket);
        User userRequest = new User();
        userRequest.setUserName(userName);
        final User user = userDao.selectOne(userRequest);
        if (user == null) {
            throw new RuntimeException("系统中不存在该用户");
        }
       // 根据用户Id去查询我们的数据，权限验证
        List<String> permissionList = new ArrayList<>();
        // userDao.selectPermission(user1.getId());
        permissionList.add("hello");
        //封装成UserDetails对象返回
        LoginUser loginUser = new LoginUser(user, permissionList);
        //注意，这里用到了自定义Token的第二个构造方法，它将告诉oauth此时已经通过认证。
        //但是，如果UserDetails对象为null，后面的逻辑将抛出异常，认证还是过不去。
        CasTickAuthenticationToken authenticationToken = new CasTickAuthenticationToken(loginUser, loginUser.getAuthorities());
        //返回一个通过认证的自定义token对象，大功告成
        return authenticationToken;
    }


    /**
     * 验证逻辑
     * @param ticket
     * @return
     */
    private String ticketValidator(String ticket) {

        return "admin";
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return CasTickAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
